import 'dart:async';
import 'dart:ui';
import 'package:dio/dio.dart';
import 'package:kzcity_picker/kzcity_picker.dart';
import 'package:magic_car/UI/webview.dart';
import 'package:magic_car/baoxiu/brandselect.dart';
import 'package:magic_car/baoxiu/cartype.dart';
import 'package:magic_car/baoxiu/xieyi.dart';
import 'package:magic_car/jiance/b_gurateedetial.dart';
import 'package:magic_car/res/colors.dart';
import 'package:magic_car/util/config.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:toast/toast.dart';
import 'package:flutter/material.dart';
import 'package:magic_car/util/HttpHelper.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:io';
import 'package:date_format/date_format.dart';
import 'package:fluwx/fluwx.dart' as fluwx;
import 'package:flutter_picker/Picker.dart';
// import 'package:amap_location/amap_location.dart';
import 'package:permission_handler/permission_handler.dart';

// import 'package:amap_search_fluttify/amap_search_fluttify.dart';
class GuaranteePage extends StatefulWidget {
  // GuaranteePage({Key key, this.title}) : super(key: key);

  // final String title;
  final String oid;
  final int type; //1 为车源下单，2为购买质保
  GuaranteePage(this.oid, this.type);

  @override
  _MyHomePageState createState() => new _MyHomePageState(this.oid);
}

class _MyHomePageState extends State<GuaranteePage> {
  final String oid;
  _MyHomePageState(this.oid);
  TextEditingController _nametroller = new TextEditingController();
  TextEditingController _address = new TextEditingController();
  TextEditingController _mobiletroller = new TextEditingController();
  TextEditingController _pricetroller = new TextEditingController();
  TextEditingController _idcardtroller = new TextEditingController();
  TextEditingController _expricetroller = new TextEditingController();
  TextEditingController _passtroller = new TextEditingController();
  TextEditingController _confirmpasstroller = new TextEditingController();
  TextEditingController _validtroller = new TextEditingController();
  List formList;
  bool agreen = false;
  File _image;
  String card_z = '';
  String card_f = '';
  bool select_img = false;
  List typelist = [
    {'title': '半年1万公里  价格460元', 'value': '460', 'type': '1'},
    {'title': '1年2万公里  价格860元', 'value': '860', 'type': '2'},
  ];
  List products = [];
  int type_index = 100;
  String type_str = '';
  double lng;
  double lat;
  List provincedatalist = [];
  var provinceName = "";
  var provinceId = "";
  var cityName = "";
  var cityId = "";
  var areaName = "";
  var areaId = "";
  String areaStr = "选择地区";
  String _verifyStr = "获取验证码";
  Timer _timer;
  int _seconds = 60;
  var userinfo;

  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

  initState() {
    super.initState();
    startLcoations();

    fluwx.weChatResponseEventHandler.listen((res) {
      print(res);
      if (res is fluwx.WeChatPaymentResponse) {
        if (res.isSuccessful) {
          //支付成功
          Toast.show('订单已支付，请等待系统处理', context);
        }
      }
    });

    formList = [
      {
        "title": '姓名',
        'sub_title': '云A00001',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': 1,
        'bottom': 1.0,
        'value': '',
        'code': 'name',
        'ctr': _nametroller
      },
      {
        "title": '联系电话',
        'sub_title': 'phone',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': 1,
        'bottom': 1.0,
        'value': '',
        'code': 'phone',
        'ctr': _mobiletroller
      },
      {
        "title": '验证码',
        'sub_title': 'phone',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': 100,
        'bottom': 1.0,
        'value': '',
        'code': 'validcode',
        'ctr': _validtroller
      },
      {
        "title": '保修类型',
        'sub_title': '云A00001',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': 2,
        'bottom': 10.0,
        'value': '请选择保修类型',
        'code': 'type',
        'ctr': _address
      },
      {
        "title": '所在城市',
        'sub_title': '云A00001',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': 5,
        'bottom': 1.0,
        'value': '',
        'code': 'area',
        // 'ctr': _address
      },
      {
        "title": '详细地址',
        'sub_title': '云A00001',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': 1,
        'bottom': 1.0,
        'value': '',
        'code': 'address',
        'ctr': _address
      },
      // {
      //   "title": '车价',
      //   'sub_title': '云A00001云A00001云A00',
      //   'sub_color': Color.fromRGBO(27, 182, 251, 1),
      //   'type': 1,
      //   'bottom': 10.0,
      //   'value': '',
      //   'code': ''
      // },
      // {
      //   "title": '投保人',
      //   'sub_title': '云A00001云A00001云A00',
      //   'sub_color': Color.fromRGBO(27, 182, 251, 1),
      //   'type': 1,
      //   'bottom': 1.0,
      //   'value': '',
      //   'code': ''
      // },
      // {
      //   "title": '联系电话',
      //   'sub_title': '云A00001云A00001云A00',
      //   'sub_color': Color.fromRGBO(27, 182, 251, 1),
      //   'type': 1,
      //   'bottom': 10.0,
      //   'value': '',
      //   'code': ''
      // },
      // {
      //   "title": '品牌',
      //   'sub_title': '云A00001云A00001云A00',
      //   'sub_color': Color.fromRGBO(27, 182, 251, 1),
      //   'type': 3,
      //   'bottom': 1.0,
      //   'value': '请选择品牌',
      //   'code': '',
      //   'brand_id': '',
      // },
      // {
      //   "title": '车型',
      //   'sub_title': '云A00001云A00001云A00',
      //   'sub_color': Color.fromRGBO(27, 182, 251, 1),
      //   'type': 3,
      //   'bottom': 10.0,
      //   'value': '请选择车型',
      //   'code': '',
      //   'type_id': ''
      // },
      // {
      //   "title": '车价（万）',
      //   'sub_title': '云A00001云A00001云A00',
      //   'sub_color': Color.fromRGBO(27, 182, 251, 1),
      //   'type': 1,
      //   'bottom': 10.0,
      //   'value': '',
      //   'code': 'carPirce',
      //   'ctr': _pricetroller
      // },
      // {
      //   "title": '行驶证',
      //   'sub_title': '云A00001云A00001云A00',
      //   'sub_color': Color.fromRGBO(27, 182, 251, 1),
      //   'type': 4,
      //   'bottom': 10.0,
      //   'value': '',
      //   'code': ''
      // },
    ];
    getproduct();
    getareadata();
    loaduserinfo();
  }

  //加载商家信息
  loaduserinfo() async {
    SharedPreferences pref = await SharedPreferences.getInstance();
    Map<String, String> map = new Map();
    map["id"] = pref.getString('uid');
    // setState(() {
    //   agent = pref.getString('agent').toString();
    // });

    HttpHelper.post(HttpHelper.API_BusinessInfo, (data) async {
      if (data != null) {
        print(data);
        //Toast.show(data["msg"], context);

        if (data["code"].toString() == "1") {
          setState(() {
            userinfo = data["info"];
            _nametroller.text = data["info"]["name"];
            _mobiletroller.text = data["info"]["mobile"];
            _address.text = data["info"]["address"];
            areaStr =
                "${userinfo['provinceName']}/${userinfo['cityName']}/${userinfo['areaName']}";
            provinceName = "${userinfo['provinceName']}";
            cityName = "${userinfo['cityName']}";
            areaName = "${userinfo['areaName']}";
          });
          //pref.setStringList('userinfo', data["info"]);

        }
      }
    }, params: map);
  }

  getareadata() {
    Map<String, String> map = new Map();

    HttpHelper.post(HttpHelper.API_Area_data, (data) {
      if (data != null) {
        print(data);

        if (data["status"].toString() == "1") {
          // Navigator.pop(context);
          setState(() {
            provincedatalist = data['result']['defaultList'];
          });
        }
      }
    }, params: map);
  }

  Widget layout() {
    List<Widget> tiles = [];
    Widget content;
    for (var item in formList) {
      var type = item["type"];
      if (type == 1) {
        //输入框
        tiles.add(inputWidget(item));
      } else if (type == 2) {
        //时间选择
        tiles.add(dateSelect(item));
      } else if (type == 3) {
        //类型选择
        tiles.add(cartype(item));
      } else if (type == 4) {
        //图片
        tiles.add(imagUp(item));
      } else if (type == 5) {
        tiles.add(selectcity(item));
      } else if (type == 100) {
        tiles.add(validcodeWidget(item));
      }
    }

    var agreen = Padding(
        padding: new EdgeInsets.fromLTRB(10, 10, 0, 0),
        child: Row(
          // crossAxisAlignment: CrossAxisAlignment.baseline,
          children: <Widget>[
            // Expanded(
            //   flex: 1,
            //   child:
            Container(
              alignment: new FractionalOffset(0.0, 0.0),
              width: 20,
              height: 20,
              child: Checkbox(
                activeColor: Color.fromRGBO(27, 182, 251, 1),
                checkColor: Colors.blue,
                value: this.agreen,
                onChanged: (value) {
                  setState(() {
                    this.agreen = value;
                  });
                },
              ),
            ),
            // Expanded(
            //   flex:2,
            //   child:
            Padding(
                padding: new EdgeInsets.fromLTRB(5, 0, 0, 0),
                child: Container(
                    child: GestureDetector(
                  onTap: () {
                    Navigator.of(context)
                        .push(new MaterialPageRoute(builder: (_) {
                      return new GurateenAgreementPage();
                    }));
                  },
                  child: RichText(
                    text: TextSpan(
                        text: '我已经阅读并同意',
                        style: TextStyle(
                            fontSize: 12, color: Color.fromRGBO(51, 51, 51, 1)),
                        children: [
                          TextSpan(
                              text: '【保修服务协议】',
                              style: TextStyle(
                                fontSize: 12,
                                color: Colours.app_main,
                              ))
                        ]),
                  ),
                )))
            //)
          ],
        ));
    tiles.add(agreen);
    // var btn = new SizedBox(
    //     width: double.infinity,
    //     height: 50,
    //     child: new FlatButton(
    //       child: Text('立即申请入驻'),
    //       textColor: Colors.white,
    //       color: Colors.white,
    //       //color: Color.fromRGBO(27, 182, 251, 1),
    //       onPressed: () {
    //         regist();
    //       },
    //     ));
    var btn = new Container(
        margin: new EdgeInsets.fromLTRB(0, 15, 0, 0),
        color: Color.fromRGBO(239, 239, 239, 1),
        //color:Colors.white,
        child: new Padding(
            padding: new EdgeInsets.fromLTRB(10, 0, 20, 0),
            child: new Material(
              color: Color.fromRGBO(239, 239, 239, 1),
              //INK可以实现装饰容器
              child: new Ink(
                //用ink圆角矩形
                //color: Color.fromRGBO(239, 239, 239, 1),
                decoration: new BoxDecoration(
                  //背景

                  color: Color.fromRGBO(255, 204, 48, 1),
                  //设置四周圆角 角度
                  borderRadius: BorderRadius.all(Radius.circular(18.0)),
                  //设置四周边框
                  border: new Border.all(
                      width: 1, color: Color.fromRGBO(255, 204, 48, 1)),
                ),
                child: new InkWell(

                    //圆角设置,给水波纹也设置同样的圆角
                    //如果这里不设置就会出现矩形的水波纹效果
                    borderRadius: new BorderRadius.circular(15.0),
                    //设置点击事件回调
                    onTap: () {
                      if (widget.type == 1) {
                        submit();
                      } else {
                        buygurateen();
                      }
                    },
                    child: Container(
                      //设置 child 居中
                      alignment: Alignment(0, 0),
                      height: 36,
                      //color: Color.fromRGBO(239, 239, 239, 1),
                      width: double.infinity,
                      child: Text(
                        "提    交",
                        style: TextStyle(color: Colors.white),
                      ),
                    )),
              ),
            )));

    tiles.add(btn);
    content = new Padding(
        padding: new EdgeInsets.fromLTRB(0, 0, 0, 10),
        child: new Column(
            children: tiles //重点在这里，因为用编辑器写Column生成的children后面会跟一个<Widget>[]，
            //此时如果我们直接把生成的tiles放在<Widget>[]中是会报一个类型不匹配的错误，把<Widget>[]删了就可以了
            ));
    return content;
  }

  showPicker(BuildContext context) {
    Picker picker = Picker(
        adapter: PickerDataAdapter<String>(pickerdata: products),
        changeToFirst: false,
        textAlign: TextAlign.left,
        textStyle: TextStyle(color: Colors.blue),
        selectedTextStyle: TextStyle(color: Colors.red),
        columnPadding: const EdgeInsets.all(8.0),
        confirmText: '确定',
        confirmTextStyle: TextStyle(color: Colors.black),
        cancelText: '取消',
        cancelTextStyle: TextStyle(color: Colors.black),
        onConfirm: (Picker picker, List value) {
          print(value.toString());
          print(picker.getSelectedValues());
          formList[3]['value'] = picker.getSelectedValues()[0];
          setState(() {
            formList = formList;
          });
          type_index = value[0];
          // type_index = i;
        });

    picker.show(_scaffoldKey.currentState);
  }

  startLcoations() async {
    print('开始定位');

    if (await Permission.location.request().isGranted) {
      // 干你该干的事
    }
  }

  getproduct() {
    //
    Map<String, String> param = new Map();

    HttpHelper.post(HttpHelper.API_Gurateen_product, (data) async {
      if (data != null) {
        print(data);

        if (data["code"].toString() == "1") {
          setState(() {
            typelist = data['info']['product'];
            products = data['info']['list'];
           // formList[3]['value'] = data['info']['list'][0];
          });
        }
      }
    }, params: param);
  }

  //弹出付款方式
  poppaytype(orderid, rechcek) {
    showModalBottomSheet(
        context: context,
        builder: (BuildContext context) {
          return Container(
            height: 120,
            child: Column(
              children: [
                Container(
                  height: 40,
                  decoration: BoxDecoration(
                      border: Border(
                          bottom:
                              BorderSide(width: 1, color: Colours.base_gray))),
                  child: Center(child: Text('付款方式')),
                ),
                InkWell(
                    onTap: () {
                      Navigator.pop(context);
                      paybugroup(orderid);
                      // queryprolems(type, xsz_url, chejia.text, rechcek, 4);
                    },
                    child: Container(
                      height: 40,
                      decoration: BoxDecoration(
                          border: Border(
                              bottom: BorderSide(
                                  width: 1, color: Colours.base_gray))),
                      child: Center(child: Text('套餐付费')),
                    )),
                InkWell(
                    onTap: () {
                      Navigator.pop(context);
                      pay(orderid);
                      // queryprolems(type, xsz_url, chejia.text, rechcek, 3);
                    },
                    child: Container(
                      height: 40,
                      // decoration: BoxDecoration(
                      //   border: Border(bottom: BorderSide(
                      //     width: 1,color: Colours.base_gray
                      //   ))
                      // ),
                      child: Center(child: Text('微信支付')),
                    )),
              ],
            ),
          );
        });
  }

  //购买保修
  buygurateen() async {
    FocusScope.of(context).requestFocus(FocusNode());

    if (!agreen) {
      Toast.show('请勾选协议', context);
      return;
    }

    // LoadingPage loadpage = new LoadingPage(context);
    // loadpage.show();
    print(this.formList);
    Map<String, String> param = new Map();

    param["id"] = this.oid;
    SharedPreferences pref = await SharedPreferences.getInstance();
    param["bid"] = pref.getString('uid');
    param["price"] = typelist[type_index]['value'].toString();
    param["service_type_string"] = typelist[type_index]['title'];
    param["service_type"] = typelist[type_index]['type'].toString();
    param["lat"] = lat.toString();
    param["lng"] = lng.toString();
    param['provincedata'] = provinceName;
    param['citydata'] = cityName;
    param['name'] = _nametroller.text;
    param['phone'] = _mobiletroller.text;
    param['address'] = _address.text;
    param['code'] = _validtroller.text;
    print(param);
    HttpHelper.post(HttpHelper.API_Bussinessbuyguranteen, (data) async {
      if (data != null) {
        print(data);
        Toast.show(data["result"]["message"], context);

        if (data["status"].toString() == "1") {
          Navigator.of(context).push(new MaterialPageRoute(builder: (_) {
            return new GurateedetailPage(data["result"]['order_id'].toString());
          }));
          //  poppaytype(data["result"]['order_id'], 1);
          //  pay(data["result"]['order_id']);
        }
      }
    }, params: param);
  }

//提交保修
  submit() async {
    FocusScope.of(context).requestFocus(FocusNode());

    if (!agreen) {
      Toast.show('请勾选协议', context);
      return;
    }
    if(type_index==100){
        Toast.show('请选择保修产品类型', context);
      return;
    }

    // LoadingPage loadpage = new LoadingPage(context);
    // loadpage.show();
    print(this.formList);
    Map<String, String> param = new Map();

    param["car_id"] = this.oid;
    SharedPreferences pref = await SharedPreferences.getInstance();
    param["bid"] = pref.getString('uid');
    param["price"] = typelist[type_index]['value'].toString();
    param["service_type_string"] = typelist[type_index]['title'];
    param["service_type"] = typelist[type_index]['type'].toString();
    param["lat"] = lat.toString();
    param["lng"] = lng.toString();
    param['provinceName'] = provinceName;
    param['cityName'] = cityName;
    param['name'] = _nametroller.text;
    param['mobile'] = _mobiletroller.text;
    param['address'] = _address.text;
    param['code'] = _validtroller.text;
    print(param);
    HttpHelper.post(HttpHelper.API_Guratee, (data) async {
      if (data != null) {
        print(data);
        Toast.show(data["result"]["message"], context);

        if (data["status"].toString() == "1") {
          Navigator.of(context).push(new MaterialPageRoute(builder: (_) {
            return new GurateedetailPage(data["result"]['order_id'].toString());
          }));
          //  poppaytype(data["result"]['order_id'], 1);
          //  pay(data["result"]['order_id']);
        }
      }
    }, params: param);
  }

  paybugroup(orderid) {
    Map<String, String> param = new Map();
    param['order_id'] = orderid;
    param['use_group'] = "1";
    HttpHelper.post(HttpHelper.API_pay, (data) async {
      //loadpage.close();
      //loadpage.close();
      if (data != null) {
        if (data["status"].toString() == "1") {
          var payinfo = data['result']['message'];
          Toast.show(payinfo, context);
        } else {
          var payinfo = data['result']['message'];
          Toast.show(payinfo, context);
        }
      }
    }, params: param);
  }

  pay(oid) {
    Map<String, String> param = new Map();
    param['order_id'] = oid;
    HttpHelper.post(HttpHelper.API_pay, (data) async {
      //loadpage.close();
      //loadpage.close();
      if (data != null) {
        if (data["status"].toString() == "1") {
          var payinfo = data['result']['pay_info'];
          print(payinfo['prepayid']['0']);
          fluwx.payWithWeChat(
              appId: Config.wx_appid,
              partnerId: payinfo['partnerid'],
              prepayId: payinfo['prepayid']['0'],
              packageValue: payinfo['package'],
              nonceStr: payinfo['noncestr'],
              timeStamp: int.parse(payinfo['timestamp']),
              sign: payinfo['sign']);
        }
      }
    }, params: param);
  }

  //获取验证码
  //发送验证码
  sendcode() {
    FocusScope.of(context).requestFocus(FocusNode());

    if (_mobiletroller.text.trim().length == 0) {
      Toast.show("填写手机号", context);
      return;
    }
    Map<String, String> map = new Map();
    map["mobile"] = _mobiletroller.text.trim();
    HttpHelper.post(HttpHelper.API_SendCode, (data) {
      if (data != null) {
        print(data);
        Toast.show(data["msg"], context);

        if (data["code"].toString() == "1") {
          // Navigator.pop(context);
          _startTimer();
          setState(() {
            // orderInfo=data["data"];
          });
        }
      }
    }, params: map);
  }

  void _startTimer() {
    print('开始计时');
    // 计时器（`Timer`）组件的定期（`periodic`）构造函数，创建一个新的重复计时器。
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      print(_seconds.toString());
      if (_seconds == 0) {
        _cancelTimer();

        setState(() {
          _verifyStr = '重新发送';
          _seconds = 60;
        });
        return;
      }

      _verifyStr = '已发送$_seconds' + 's';
      setState(() {
        _verifyStr = '已发送$_seconds' + 's';
      });
      _seconds--;
      if (_seconds == 0) {
        _verifyStr = '重新发送';
      }
    });
  }

  /// 取消倒计时的计时器。
  void _cancelTimer() {
    print('取消');
    // 计时器（`Timer`）组件的取消（`cancel`）方法，取消计时器。
    _timer?.cancel();
  }

  //输入验证码的组件
  Widget validcodeWidget(item) {
    var valid = Padding(
        padding: new EdgeInsets.fromLTRB(0, 1, 0, 1),
        child: Container(
          color: Colors.white,
          height: 50,
          child: new Row(
            children: <Widget>[
              Expanded(
                child: new Padding(
                    padding: new EdgeInsets.fromLTRB(10, 0, 10, 0),
                    child: new Text(
                      '验证码',
                      style: TextStyle(
                          fontSize: 15,
                          color: Color.fromRGBO(102, 102, 102, 1)),
                    )),
                flex: 1,
              ),
              Expanded(
                child: Align(
                    alignment: Alignment.centerRight,
                    child: new Padding(
                        padding: new EdgeInsets.fromLTRB(10, 0, 10, 0),
                        child: new TextField(
                            textAlign: TextAlign.end,
                            controller: _validtroller,
                            decoration: InputDecoration(
                              contentPadding:
                                  const EdgeInsets.symmetric(vertical: 4.0),
                              hintText: '验证码',
                              hintStyle:
                                  TextStyle(fontSize: Config.hit_base_size),
                              border: OutlineInputBorder(
                                borderSide: BorderSide.none,
                              ),
                            )))),
                flex: 1,
              ),
              Expanded(
                child: new Padding(
                  padding: new EdgeInsets.fromLTRB(10, 0, 10, 0),
                  child: Align(
                      alignment: Alignment.centerRight,
                      child: new Container(
                        child: new Material(
                          //INK可以实现装饰容器
                          child: new Ink(
                            //用ink圆角矩形
                            // color: Colors.red,
                            decoration: new BoxDecoration(
                              //背景
                              color: Colors.white,
                              //设置四周圆角 角度
                              borderRadius:
                                  BorderRadius.all(Radius.circular(5.0)),
                              //设��四周边框
                              border: new Border.all(
                                  width: 1, color: Colours.app_main),
                            ),
                            child: new InkWell(
                                //圆角设置,给水波纹也设置同样的圆角
                                //如果这里不设置就会出现矩形的水波纹效果
                                borderRadius: new BorderRadius.circular(15.0),
                                //设置点击事件回调
                                onTap: () {
                                  if (_seconds == 60) {
                                    sendcode();
                                  }
                                },
                                child: Container(
                                  //设置 child 居中
                                  alignment: Alignment(0, 0),
                                  height: 35,
                                  width: 105,
                                  child: Text(_verifyStr,
                                      style:
                                          TextStyle(color: Colours.app_main)),
                                )),
                          ),
                        ),
                      )
                      // child: new RaisedButton(
                      //   child: Text('申请补考'),
                      //   onPressed: () {},
                      // ),
                      ),
                  // child: new RaisedButton(
                  //   onPressed: () {
                  //     sendcode();
                  //   },
                  //   child: Text('获取验证码'),
                  // ),
                ),
                flex: 1,
              )
            ],
          ),
        ));
    return valid;
  }

  //输入框组件
  Widget inputWidget(item) {
    Widget content = Padding(
        padding: new EdgeInsets.fromLTRB(0, 0, 0, item["bottom"]),
        child: Container(
          color: Colors.white,
          height: 50,
          child: new Row(
            children: <Widget>[
              Expanded(
                child: new Padding(
                  padding: new EdgeInsets.fromLTRB(10, 0, 10, 0),
                  child: RichText(
                    text: TextSpan(
                        text: item["title"],
                        style: TextStyle(
                            fontSize: 15,
                            color: Color.fromRGBO(102, 102, 102, 1)),
                        children: [
                          // TextSpan(
                          //     text: '*',
                          //     style: TextStyle(fontSize: 14, color: Colors.red))
                        ]),
                  ),
                ),
                flex: 1,
              ),
              Expanded(
                child: new Padding(
                    padding: new EdgeInsets.fromLTRB(10, 0, 10, 0),
                    child: new TextField(
                      controller: item["ctr"],
                      textAlign: TextAlign.right,
                      // controller: _nametroller,
                      decoration: InputDecoration(
                        hintText: '请输入' + item["title"],
                        border: OutlineInputBorder(
                          borderSide: BorderSide.none,
                        ),
                      ),
                      onChanged: (val) {
                        print(val);
                        item["value"] = val;
                      },
                    )),
                flex: 2,
              )
            ],
          ),
        ));
    return content;
  }

  //城市选择
  Widget selectcity(item) {
    Widget content = Padding(
        padding: new EdgeInsets.fromLTRB(0, 0, 0, item["bottom"]),
        child: Container(
          color: Colors.white,
          height: 50,
          child: new Row(
            children: <Widget>[
              Expanded(
                child: new Padding(
                  padding: new EdgeInsets.fromLTRB(10, 0, 10, 0),
                  child: RichText(
                    text: TextSpan(
                        text: item["title"],
                        style: TextStyle(
                            fontSize: 15,
                            color: Color.fromRGBO(102, 102, 102, 1)),
                        children: [
                          // TextSpan(
                          //     text: '*',
                          //     style: TextStyle(fontSize: 14, color: Colors.red))
                        ]),
                  ),
                ),
                flex: 1,
              ),
              Expanded(
                child: Padding(
                    padding: new EdgeInsets.fromLTRB(10, 0, 20, 0),
                    child: Align(
                        alignment: Alignment.centerRight,
                        child: new GestureDetector(
                            child: new Text(areaStr),
                            onTap: () async {
                              FocusScope.of(context).requestFocus(FocusNode());
                              final result = await KzcityPicker.showPicker(
                                  context,
                                  datas: provincedatalist);

                              if (result != null) {
                                setState(() {
                                  provinceName = result.province;
                                  provinceId = result.provinceCode.toString();
                                  cityName = result.city;
                                  cityId = result.cityCode.toString();
                                  areaName = result.area;
                                  areaId = result.areaCode.toString();
                                  setState(() {
                                    areaStr =
                                        provinceName + cityName + areaName;
                                  });
                                });
                              }
                              // showPicker(context);
                              //  showModalBottomSheet(
                              // context: context,
                              // builder: (BuildContext context) {
                              //   return showDate();
                              // });
                            }))),
                flex: 2,
              )
            ],
          ),
        ));
    return content;
  }

  //日期选择组件
  Widget dateSelect(item) {
    DateTime initialDate = DateTime.now();
    Widget content = Padding(
        padding: new EdgeInsets.fromLTRB(0, 0, 0, item["bottom"]),
        child: Container(
          color: Colors.white,
          height: 50,
          child: new Row(
            children: <Widget>[
              Expanded(
                child: new Padding(
                  padding: new EdgeInsets.fromLTRB(10, 0, 10, 0),
                  child: RichText(
                    text: TextSpan(
                        text: item["title"],
                        style: TextStyle(
                            fontSize: 15,
                            color: Color.fromRGBO(102, 102, 102, 1)),
                        children: [
                          // TextSpan(
                          //     text: '*',
                          //     style: TextStyle(fontSize: 14, color: Colors.red))
                        ]),
                  ),
                ),
                flex: 1,
              ),
              Expanded(
                child: Padding(
                    padding: new EdgeInsets.fromLTRB(10, 0, 20, 0),
                    child: Align(
                        alignment: Alignment.centerRight,
                        child: new GestureDetector(
                            child: new Text(item["value"]),
                            onTap: () async {
                              FocusScope.of(context).requestFocus(FocusNode());
                              showPicker(context);
                              //  showModalBottomSheet(
                              // context: context,
                              // builder: (BuildContext context) {
                              //   return showDate();
                              // });
                            }))),
                flex: 2,
              )
            ],
          ),
        ));
    return content;
  }

  //车辆类型组件
  Widget cartype(item) {
    Widget content = Padding(
        padding: new EdgeInsets.fromLTRB(0, 0, 0, item["bottom"]),
        child: Container(
            color: Colors.white,
            height: 50,
            child: new GestureDetector(
              onTap: () {
                // print('选择车型');
                // Navigator.pushNamed(context, 'brand');
                if (item.containsKey("brand_id")) {
                  Navigator.of(context)
                      .push(new MaterialPageRoute(builder: (_) {
                    return new BrandSelectRoute(item);
                  }));
                } else {
                  Navigator.of(context)
                      .push(new MaterialPageRoute(builder: (_) {
                    return new CartypeSelectRoute(
                        item, formList[3]["brand_id"], '0');
                  }));
                }
              },
              child: new Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: <Widget>[
                  Expanded(
                    child: new Padding(
                      padding: new EdgeInsets.fromLTRB(10, 0, 10, 0),
                      child: RichText(
                        text: TextSpan(
                            text: item["title"],
                            style: TextStyle(
                                fontSize: 15,
                                color: Color.fromRGBO(102, 102, 102, 1)),
                            children: [
                              // TextSpan(
                              //     text: '*',
                              //     style: TextStyle(fontSize: 14, color: Colors.red))
                            ]),
                      ),
                    ),
                  ),
                  //  Expanded(
                  //   child:
                  new Padding(
                    padding: new EdgeInsets.fromLTRB(10, 0, 0, 0),
                    child: RichText(
                      text: TextSpan(
                          text: item["value"],
                          style: TextStyle(
                              fontSize: 15,
                              color: Color.fromRGBO(102, 102, 102, 1)),
                          children: [
                            // TextSpan(
                            //     text: '*',
                            //     style: TextStyle(fontSize: 14, color: Colors.red))
                          ]),
                    ),
                  ),

                  //),
                  // Expanded(
                  //   child:
                  Padding(
                      padding: new EdgeInsets.fromLTRB(10, 0, 20, 0),
                      child: Align(
                          alignment: Alignment.centerRight,
                          child: Image.asset(
                            'resource/images/user/detail.png',
                            height: 20,
                          ))),

                  // )
                ],
              ),
            )));
    return content;
  }

  Widget dateView() {
    List<Widget> tiles = [];
    Widget content;
    for (var i = 0; i < typelist.length; i++) {
      var item = typelist[i];
      tiles.add(GestureDetector(
          onTap: () {
            setState(() {
              // time_str = item;
              formList[3]['value'] = item['title'];
              type_index = i;
            });
            //  caculatorDays(item);

            Navigator.of(context).pop();
          },
          child: Container(
              height: 40, child: Center(child: new Text(item['title'])))));
    }

    content = new Column(
        children: tiles //重点在这里，因为用编辑器写Column生成的children后面会跟一个<Widget>[]，
        //此时如果我们直接把生成的tiles放在<Widget>[]中是会报一个类型不匹配的错误，把<Widget>[]删了就可以了
        );
    return content;
  }

  Widget showDate() {
    return new Container(
      height: 200.0,
      child: new Column(
        children: <Widget>[
          new Padding(
            padding: EdgeInsets.fromLTRB(0.0, 10.0, 0.0, 0.0),
            child: new Container(
                height: 140.0,
                child: new ListView(children: <Widget>[dateView()])),
            // child: new Container(
            //   height: 240.0,

            //   )
            //     },
            //     itemCount: insepcetor.length,
            //   ),
            // ),
          ),
          new Container(
            height: 0.5,
            color: Colors.blueGrey,
          ),
          new Center(
            child: new Padding(
              padding: EdgeInsets.fromLTRB(0.0, 8.0, 0.0, 8.0),
              child: GestureDetector(
                  behavior: HitTestBehavior.opaque,
                  onTap: () {
                    Navigator.of(context).pop();
                  },
                  child: new Text(
                    '取  消',
                    style:
                        new TextStyle(fontSize: 18.0, color: Colors.blueGrey),
                  )),
            ),
          ),
        ],
      ),
    );
  }

  //图片上传组件
  Widget imagUp(item) {
    Widget content = Padding(
        padding: new EdgeInsets.fromLTRB(0, 0, 0, item["bottom"]),
        child: Container(
          color: Colors.white,
          height: 160,
          child: new Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              new Padding(
                padding: new EdgeInsets.fromLTRB(10, 10, 10, 0),
                child: RichText(
                  text: TextSpan(
                      text: item["title"],
                      style: TextStyle(
                          fontSize: 15,
                          color: Color.fromRGBO(102, 102, 102, 1)),
                      children: [
                        // TextSpan(
                        //     text: '*',
                        //     style: TextStyle(fontSize: 14, color: Colors.red))
                      ]),
                ),
              ),
              Padding(
                  padding: new EdgeInsets.fromLTRB(0, 0, 0, 0),
                  child: Container(
                    color: Colors.white,
                    height: 100,
                    child: new Row(
                      children: <Widget>[
                        Expanded(
                            child: new Padding(
                              padding: new EdgeInsets.fromLTRB(0, 0, 10, 10),
                              child: new GestureDetector(
                                  onTap: () {
                                    getImage(1);
                                  },
                                  child: FadeInImage.assetNetwork(
                                    placeholder:
                                        "resource/images/user/upimg.png",
                                    image: card_z,
                                  )),
                              // new Image.asset('resource/images/user/card_img1.png'),
                            ),
                            flex: 1),
                        Expanded(
                            child: new Padding(
                              padding: new EdgeInsets.fromLTRB(0, 0, 10, 10),
                              child: new GestureDetector(
                                  onTap: () {
                                    getImage(2);
                                  },
                                  child: FadeInImage.assetNetwork(
                                    placeholder:
                                        "resource/images/user/upimg.png",
                                    image: card_f,
                                  )),
                              // new Image.asset('resource/images/user/card_img2.png'),
                            ),
                            flex: 1),
                      ],
                    ),
                  )),

              //  Expanded(
              //   child:
            ],
          ),
        ));
    return content;
  }

//发送验证码
  // sendcode() {
  //   print('获取验证码');
  //   if (_mobiletroller.text.trim().length == 0) {
  //     Toast.show("填写手机号", context);
  //     return;
  //   }
  //   Map<String, String> map = new Map();
  //   map["mobile"] = _mobiletroller.text.trim();
  //   HttpHelper.post(HttpHelper.API_SendCode, (data) {
  //     if (data != null) {
  //       print(data);
  //       Toast.show(data["result"]["message"], context);

  //       if (data["status"].toString() == "0") {
  //         // Navigator.pop(context);

  //         setState(() {
  //           // orderInfo=data["data"];
  //         });
  //       }
  //     }
  //   }, params: map);
  // }

  //选择图片
  getimgs(type, card) async {
    if (type == 1) {
      var image = await ImagePicker.pickImage(source: ImageSource.gallery);

      setState(() {
        _image = image;
        select_img = true;
      });
    } else {
      var image = await ImagePicker.pickImage(source: ImageSource.camera);

      setState(() {
        _image = image;
        select_img = true;
      });
    }
    if (_image == null) return;
    Map<String, String> map = new Map();

    HttpHelper.upLoadImage(_image, (data) {
      if (card == 1) {
        setState(() {
          card_z = data["url"];
        });
      } else {
        card_f = data["url"];
      }
    }, params: map);
  }

//选择图片�����
  Future getImage(type) async {
    showDialog(
        context: context,
        builder: (BuildContext context) {
          return new SimpleDialog(
            title: new Text('选择'),
            children: <Widget>[
              new SimpleDialogOption(
                child: new Text('相机'),
                onPressed: () {
                  Navigator.pop(context);
                  getimgs(0, type);
                },
              ),
              new SimpleDialogOption(
                child: new Text('相册'),
                onPressed: () {
                  Navigator.pop(context);
                  getimgs(1, type);
                },
              )
            ],
          );
        });
    // var image = await ImagePicker.pickImage(source: ImageSource.gallery);
    // //_upLoadImage(image);//上传图片
    // setState(() {
    //   _image = image;
    // });
  }

  Widget build(BuildContext context) {
    return new Scaffold(
        key: _scaffoldKey,
        appBar: new AppBar(
          titleSpacing: 0,
          title: new Text(
            '保修',
            style: TextStyle(fontSize: Config.title_size),
          ),
          backgroundColor: Colors.white,
          elevation: 0,
          // backgroundColor: Color.fromRGBO(255, 204, 48, 1),
        ),
        body: new Center(
            child: Container(
                decoration: new BoxDecoration(
                  color: Colours.base_page_color,
                ),
                child: Padding(
                    padding: new EdgeInsets.fromLTRB(0, 15, 0, 0),
                    child: Stack(
                      children: <Widget>[
                        Align(
                          alignment: Alignment.topCenter,
                          child: new ListView(children: <Widget>[layout()]),
                        ),
                        Align(
                            // alignment: Alignment.bottomLeft,
                            // child: SizedBox(
                            //   width: double.infinity,
                            //   height: 50,
                            //   child: new Container(
                            //    // color: Colors.red,
                            //     child: Padding(
                            //       padding: new EdgeInsets.fromLTRB(15, 0, 15, 0),
                            //       child: Padding(
                            //         padding:
                            //             new EdgeInsets.fromLTRB(10, 10, 10, 40),
                            //         child: new SizedBox(

                            //             width: double.infinity,
                            //             height: 50,
                            //             child: new RaisedButton(
                            //               child: Text('立即申请入驻'),
                            //               textColor: Colors.white,
                            //               color: Colors.white,
                            //               //color: Color.fromRGBO(27, 182, 251, 1),
                            //               onPressed: () {
                            //                 regist();
                            //               },
                            //             )),
                            //       ),
                            //     ),

                            //   ),
                            // ),
                            )
                      ],
                    )
                    // new ListView(
                    //   children: <Widget>[buildcontent()],
                    // )),
                    ))));
  }
}
